<?php
namespace plugin\ky_shouyin\app\controller\front;

use support\Request;
use support\Db;
use support\Log;
use plugin\sms\api\Sms;
use plugin\ky_shouyin\app\controller\BaseController;

class MemberController extends BaseController
{
    /**
     * 会员开卡页面
     */
    public function index()
    {
        return $this->view('front/member/index');
    }
    
    /**
     * 会员开卡表单页
     */
    public function add()
    {
        return $this->view('front/member/add');
    }
    
    /**
     * 获取会员等级列表
     */
    public function getLevels()
    {
        $levels = Db::table('ky_member_level')
            ->where('status', 1)
            ->orderBy('points', 'asc')
            ->get();
            
        return json(['code' => 0, 'msg' => 'ok', 'data' => $levels]);
    }
    
    /**
     * 获取门店列表
     */
    public function getStores()
    {
        $stores = Db::table('ky_store')
            ->where('status', 1)
            ->orderBy('id', 'asc')
            ->get();
            
        return json(['code' => 0, 'msg' => 'ok', 'data' => $stores]);
    }
    
    /**
     * 会员开卡
     */
    public function register(Request $request)
    {
        $data = $request->post();
        
        try {
            // 处理卡号格式
            if (!empty($data['card_no'])) {
                $cardNo = strtoupper($data['card_no']);
                if (!str_starts_with($cardNo, 'VIP')) {
                    $cardNo = 'VIP' . $cardNo;
                }
                $data['card_no'] = $cardNo;
            }
            
            // 验证手机号是否已注册
            $exists = Db::table('ky_member')
                ->where('phone', $data['phone'])
                ->exists();
                
            if ($exists) {
                return json(['code' => 1, 'msg' => '该手机号已注册']);
            }
            
            // 验证卡号是否已存在
            $cardExists = Db::table('ky_member')
                ->where('card_no', $data['card_no'])
                ->exists();
                
            if ($cardExists) {
                return json(['code' => 1, 'msg' => '该会员卡号已存在']);
            }
            
            // 创建会员
            $memberId = Db::table('ky_member')->insertGetId([
                'card_no' => $data['card_no'],
                'name' => $data['name'],
                'phone' => $data['phone'],
                'password' => password_hash($data['password'], PASSWORD_DEFAULT),
                'birthday' => $data['birthday'],
                'gender' => $data['gender'],
                'level' => $data['level_id'],
                'store_id' => $data['store_id'],
                'balance' => $data['init_amount'] ?? 0,
                'points' => 0,
                'status' => 1,
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            // 如果有初始充值金额，创建充值记录
            if (!empty($data['init_amount']) && $data['init_amount'] > 0) {
                Db::table('ky_member_recharge')->insert([
                    'member_id' => $memberId,
                    'amount' => $data['init_amount'],
                    'payment_method' => $data['payment_method'],
                    'store_id' => $data['store_id'],
                    'staff_id' => session('staff_id'),
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            }
            
            return json(['code' => 0, 'msg' => '开卡成功', 'data' => ['member_id' => $memberId]]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '开卡失败：' . $e->getMessage()]);
        }
    }

    public function recharge()
    {
        return $this->view('front/member/recharge');
    }

    /**
     * 获取会员信息
     */
    public function getMember(Request $request)
    {
        $searchKey = $request->get('search_key');
        $searchType = $request->get('search_type', 'phone');
        
        if (empty($searchKey)) {
            return json(['code' => 1, 'msg' => '请输入' . ($searchType === 'phone' ? '手机号' : '会员卡号')]);
        }
        
        // 查询会员信息
        $member = Db::table('ky_member')
            ->leftJoin('ky_member_card', 'ky_member.id', '=', 'ky_member_card.member_id')
            ->where($searchType === 'phone' ? 'ky_member.phone' : 'ky_member_card.card_no', $searchKey)
            ->where('ky_member.status', 1)
            ->select([
                'ky_member.*',
                'ky_member_card.card_no'
            ])
            ->first();
            
        if (!$member) {
            return json(['code' => 1, 'msg' => '未找到会员信息']);
        }
        
        return json(['code' => 0, 'msg' => 'ok', 'data' => $member]);
    }

    /**
     * 会员充值
     */
    public function doRecharge(Request $request)
    {
        if ($request->method() === 'POST') {
            $data = $request->post();
            
            // 输入验证
            if (empty($data['member_id']) || empty($data['amount']) || $data['amount'] <= 0) {
                return json(['code' => 1, 'msg' => '无效的输入数据']);
            }
            
            try {
                Db::beginTransaction();
                
                // 验证会员是否存在
                $member = Db::table('ky_member')->where('id', $data['member_id'])->first();
                if (!$member) {
                    return json(['code' => 1, 'msg' => '会员不存在']);
                }
                //如果状态是冻结或者注销状态不可以充值
                if($member->status == 2){
                    return json(['code' => 1, 'msg' => '会员冻结了，需先恢复正常才能充值']);
                }
                if($member->status == 3){
                    return json(['code' => 1, 'msg' => '会员注销了，无法充值']);
                }

                // 生成订单号
                $orderNo = 'CZ' . time() . rand(1000, 9999);

                $operatorId = session('user.id');
                $storeId = session('user.store_id');
                
                // 计算总金额
                $totalAmount = $data['amount'] + ($data['give_amount'] ?? 0);
                $newBalance = $member->balance + $totalAmount;
                // 记录充值
                Db::table('ky_member_recharge')->insert([
                    'member_id' => $data['member_id'],
                    'amount' => $data['amount'],
                    'give_amount' => $data['give_amount'] ?? 0,
                    'payment_method' => $data['pay_type'],
                    'remark' => $data['remark'] ?? '',
                    'order_no' => $orderNo,
                    'created_at' => date('Y-m-d H:i:s'),
                    'operator_id' => $operatorId,
                    'staff_id' => $operatorId,
                    'store_id' => $storeId
                ]);

                // 更新会员余额
                Db::table('ky_member')->where('id', $data['member_id'])->increment('balance', $totalAmount);

                Db::commit();
                
                // 发送充值短信通知
                try {
                    // 准备短信模板变量
                    $templateParams = [
                        'name' => $member->name,
                        'money' => $data['amount'],
                        'blance' =>$newBalance
                    ];
                    $to = $member->phone;
                    $tagName = 'ky_user_cz';
                    $gateway = 'aliyun';
                    Sms::sendByTag($to, $tagName, $templateParams, [$gateway]);
                   
                } catch (\Exception $e) {
                    // 记录短信发送失败日志，但不影响充值业务
                    Log::error('充值短信发送失败：' . $e->getMessage());
                }

                return json(['code' => 0, 'msg' => '充值成功']);
            } catch (\Exception $e) {
                Db::rollBack();
                return json(['code' => 1, 'msg' => '充值失败：' . $e->getMessage()]);
            }
        }
    }

    public function rechargeLog(Request $request)
    {
        $memberId = $request->input('member_id');
        
        $logs = Db::table('ky_member_recharge')
            ->where('member_id', $memberId)
            ->orderBy('created_at', 'desc')
            ->get();
        
        return json(['code' => 0, 'msg' => 'success', 'data' => $logs]);
    }

    /**
     * 获取充值记录列表
     */
    public function rechargeList(Request $request)
    {
     
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 15);
        $memberId = $request->input('member_id');

        $query = Db::table('ky_member_recharge')
            ->leftJoin('ky_member', 'ky_member_recharge.member_id', '=', 'ky_member.id')
            ->leftJoin('ky_store', 'ky_member_recharge.store_id', '=', 'ky_store.id')
            ->leftJoin('ky_staff', 'ky_member_recharge.staff_id', '=', 'ky_staff.id')
            ->select(
                'ky_member_recharge.*',
                'ky_member.name as member_name',
                'ky_member.phone as member_phone',
                'ky_store.name as store_name',
                'ky_staff.name as staff_name'
            );
            
         $query->where('ky_member_recharge.member_id', $memberId);
       
        $total = $query->count();
        $list = $query->offset(($page - 1) * $limit)
                      ->limit($limit)
                      ->orderBy('ky_member_recharge.id', 'desc')
                      ->get();
        
        $total = $query->count();
        

        
        return json([
            'code' => 0,
            'msg' => 'ok',
            'count' => $total,
            'data' => $list
        ]);
    }
} 